package com.hospital.openfeign.component;

import com.hospital.common.core.result.ErrorTip;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Order(-1)
public class GlobalExceptionHandler  implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if(response.isCommitted()){
            return Mono.error(ex);
        }
        ErrorTip errorTip;
        if(ex instanceof ResponseStatusException){
            errorTip=responseStatusExceptionHandler(exchange,(ResponseStatusException)ex);
        }else {
            errorTip=defaultExceptionHandler(exchange,ex);
        }
        return null;
    }

    private ErrorTip responseStatusExceptionHandler(ServerWebExchange exchange,ResponseStatusException ex){
        ServerHttpRequest request=exchange.getRequest();
        return new ErrorTip(ex.getRawStatusCode(),ex.getReason());
    }

    public ErrorTip defaultExceptionHandler(ServerWebExchange exchange,Throwable ex){
        return new ErrorTip(-1,ex.getMessage());
    }
}
